#include <QApplication>
#include <QDebug>
#include <qapplication.h>
#include <qcoreapplication.h>
#include <qnamespace.h>
#include <string>

#include "mainwindow.h"

#include "spdlog/fmt/bundled/format.h"
#include "spdlog/logger.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"

#include "fmt/format.h"

#include <fstream>
#include <filesystem>
#include <QFile>
#include <QFileInfo>
#include <QDir>

//初始化log日志spdlog
static void _init_global_logger() {
  // spdlog::init_thread_pool(8192, 1);

  auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  stdout_sink->set_level(spdlog::level::trace);

  std::string log_file = ROOT_DIR "logs/global.log";

  auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
      log_file, 1024 * 1024 * 2, 100);
  rotating_sink->set_level(spdlog::level::trace);

  std::vector<spdlog::sink_ptr> sinks{stdout_sink, rotating_sink};
  auto logger = std::make_shared<spdlog::logger>(std::string{"G"},
                                                 sinks.begin(), sinks.end());
  logger->set_level(spdlog::level::trace);

  logger->flush_on(spdlog::level::trace);

  spdlog::register_logger(logger);
  spdlog::set_default_logger(logger);
}

static bool _init_agv_data_dir(void)
{
  namespace fs = std::filesystem;

  auto path_str = std::string(AGV_ROOT_DIR "/data/");

  fs::path dir_path = path_str;

  if (!fs::exists(dir_path)) {
    spdlog::info("dir {} not exist", path_str);

    if (fs::create_directories(dir_path) == false) {
      spdlog::error("fs::create_directories: {} failed", path_str);
      return false;
    }

    spdlog::info("fs::create_directories: {} success", path_str);
  } 

  return true;
}

int main(int argc, char **argv) {
  QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  QApplication a(argc, argv);

  _init_global_logger();

  _init_agv_data_dir();

  spdlog::info(" ");
  spdlog::info("**************************");
  spdlog::info("**** AGV System Start ****");
  spdlog::info("**************************");

  // test fmtlib
  std::string test_str = fmt::format("{}, {}", "abc", 123);

  MainWindow m;
  m.show();

  auto ret = a.exec();

  spdlog::info("**************************");
  spdlog::info("***** AGV System End *****");
  spdlog::info("**************************");

  return ret;
}
